package com.garbagecan.cachestudy.ehcache;

import java.net.URL;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PerformanceTest {
	
	private static Log log = LogFactory.getLog(PerformanceTest.class);

	private CacheManager cacheManager;
	
	private int count = 100 * 10000;
	
	public static void main(String[]args) {
		log.info("java.io.tmpdir:" + System.getProperty("java.io.tmpdir"));

		PerformanceTest test = new PerformanceTest();
		test.start();
		test.writeToCache();
		test.readFromCache();
		
		test.stop();
	}

	private void start() {
		URL url = PerformanceTest.class.getResource("/ehcache.xml");
		cacheManager = new CacheManager(url);
		log.info(cacheManager.getDiskStorePathManager());
	}

	private void stop() {
		cacheManager.shutdown();
	}
	
	private void writeToCache() {
		cacheManager.addCache("testCache");
		long start = System.currentTimeMillis();
		Cache cache = cacheManager.getCache("testCache");
		for (int i = 0; i < count; i++) {
			cache.put(new Element("key_" + i, "value_" + i));
		}
		long stop = System.currentTimeMillis();
		System.out.println(stop - start);
	}
	
	private void readFromCache() {
		log.info("cache name size:" + cacheManager.getCacheNames().length);
		for (String name : cacheManager.getCacheNames()) {
			log.info("cache name: " + name);
		}
		
		long start = System.currentTimeMillis();
		Cache cache = cacheManager.getCache("testCache");
		List<?> keys = cache.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			Object key = keys.get(i);
			Object value = cache.get(key).getObjectValue();
			//log.info(key + ":" + cache.get(key));
			//log.info(key + ":" + value);
		}
		long stop = System.currentTimeMillis();
		System.out.println(stop - start);
	}
}
